<?php

namespace App\Admin\Controllers;

use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Show;
use App\Models\Item;
use App\Models\App;
use Encore\Admin\Widgets\Tab;
use Encore\Admin\Widgets\Table;
use Encore\Admin\Layout\Content;

class ItemController extends NoidController
{
    /**
     * Title for current resource.
     *
     * @var string
     */
    protected $title = '项目';
	protected $item_name;

    public function index(Content $content)
    {
        return $content
            ->title(__('项目管理'))
            ->description($this->description['index'] ?? trans('admin.list'))
			->breadcrumb(['text' => __('项目管理')])
            ->body($this->grid());
    }
    /**
     * Make a grid builder.
     *
     * @return Grid
     */
    protected function grid()
    {
        
		$grid = new Grid(new Item);
		$grid->disablePagination();
		$grid->disableFilter();
		$grid->disableCreateButton();
		$grid->disableRowSelector();
		$grid->disableActions();


		$grid->column('name', __('项目'))->expand(function ($model) {
			if ($this->status) {
				$apps = $model->apps()->get()->map(function ($app) {
					$re = '';	
					$opens = $app->sets['tabs'] ?? [];
					foreach(array_filter($opens) as $k=>$v){
						$comm=config('exts.'.$k);
						if( !empty($comm['manager']) ) {
							$re.="<a href='".route($comm['manager'],['app'=>$app->name])."'>".$comm['title']."管理</a><br />";
						}
					}
					$app->manages = $re;
					$app->new_sets = "<a href='".route('admin.item.set',['app_name'=>$app->name])."'>设置</a>";					
					$app->new_name = "<a href='".route('admin.apps.'.$app->name.'.index')."'>".$app->name."</a>";
					
					return $app->only(['new_name', 'title', 'new_sets','manages']);
				});
				return new Table(['应用', '名称', '设置', '管理'], $apps->toArray());
			}else{
				return '&nbsp;&nbsp;&nbsp;&nbsp;应用尚未启用';
			}
		},true);
		
		$grid->column('status', __('状态'))->display(function () {			
			return $this->status ? '<a href="'.route('admin.item.status',['item'=>$this->name,'status'=>0]).'" title="点击更换状态"><span class="label label-default">已启用</span></a>':'<a href="'.route('admin.item.status',['item'=>$this->name,'status'=>1]).'" title="点击更换状态"><span class="label label-warning">禁用中</span></a>';
		});
		$grid->column('_title', __('介绍'))->display(function () {
			$is_dev = $this->is_dev ? '<span class="label label-warning">Dev</span>' : '';
			$desc = '<p><b>'.$this->title.'</b><span style="margin-left:25px;margin-right:5px;" class="label label-info">'.$this->ver.'</span>'.$is_dev.'</p>';
			$desc .= '作者：'.$this->author.'';
			$desc .= !empty($this->email) ? '<span style="margin-left:60px;">邮箱：<a href="mailto:'.$this->email.'">'.$this->email.'</a></span>' : '';
			$desc .= !empty($this->homepage) ? '<span style="margin-left:60px;">网站：<a href="'.$this->homepage.'" target="_balnk">'.$this->homepage.'</a></span>' : '';
			return $desc;
		});
		$grid->column('_desc', __('详情'))->display(function () {
			return '详情...';
		})->modal('项目详情', function ($model) {
			return $this->desc;
		});		

        return $grid;
    }

    /**
     * Make a set form.
     *
     * @return Form
     */
    public function set(Content $content)
    {
		//dd(get_cate('laoha_blog'));
		
		$active = request('active','base');
		$app_name = request('app_name');
		
		$app = get_app($app_name);
		$app_sets = $app['sets']??[];

		$tabs['base'] = '\\App\\Admin\\Forms\\Appsets\\Base';

		if(!empty($app['set_form'])){
			$tabs['app'] = $app['set_form'];  //自定义应用设置
		}
		foreach($app_sets['tabs'] as $k=>$v){
			if($v && !empty(config('exts.'.$k.'.set_form')) ){
				$tabs[$k] = config('exts.'.$k.'.set_form');
			}
		}
		
		return $content
            ->title(__('应用设置'))
			->breadcrumb(['text' => '项目管理','url'=>'item'],['text' => '应用设置'])
            ->body(Tab::forms($tabs));
    }



    public function status()
    {
		$item_name = request()->get('item','');
		$item = Item::findOrFail($item_name);
		$status = request()->get('status',0);
		$item->status = $status ? 1:0;
		$item->save();
		$apps = App::withoutGlobalScope('avaiable')->where('item_name',$item_name)->update(['status'=>$item->status]);

        return redirect(admin_url('item'));
    }

    /**
     * Make a form builder.
     *
     * @return Form
     */
    protected function form()
    {
        $form = new Form(new Item);
		$form->text('ver', __('当前版本'))->rules('required');
		$form->text('name', __('项目标识'))
			->creationRules('required|unique:items,name|regex:/^[a-z][a-z_]+$/',['regex' => '标识必须是英文开头且只包含小写字母、下划线'])
			->updateRules('required|unique:items,name,{{name}}|regex:/^[a-z][a-z_]+$/',['regex' => '标识必须是英文开头且只包含小写字母、下划线']);
		$form->text('title', __('项目名称'))->rules('required');
		$form->textarea('desc', __('项目介绍'))->rules('required');
		
		$form->text('author', __('项目作者'))->rules('required');
		$form->text('email', __('联系邮箱'))->rules('email');
		$form->text('homepage', __('网站首页'))->rules('url');
		$form->switch('status', __('启用状态'))->default(1);
        $form->display('created_at', __('Created At'));
        $form->display('updated_at', __('Updated At'));

        return $form;
    }
}
